package com.cishu.orancle.utils;

import com.cishu.orancle.common.CustomException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class RestfulUtils {
    /**
     * 将Map数据转为query参数类型
     * */
    private static String buildQueryParams(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder query = new StringBuilder();

        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (!query.isEmpty()) {
                query.append("&");
            }
            query.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
            query.append("=");
            query.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
        }

        return query.toString();
    }
    /**
     * GET请求封装
     * Map<String, String> headers = new HashMap<>();
     * headers.put("Cookie", "sessionId=abc123");
     * String response = GET("https://example.com/api", null, "your_token", headers);
     * */

    public static String GET(String url, Map<String, String> param, String token, Map<String, String> headers) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String newUrl = url;
            if (param != null) {
                newUrl = url + "?" + buildQueryParams(param);
            }
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(newUrl);

            HttpHeaders httpHeaders = new HttpHeaders();
            // 添加Authorization Header
            httpHeaders.add("Authorization", "Bearer " + token);

            // 添加其他Header信息
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpHeaders.add(entry.getKey(), entry.getValue());
                }
            }

            HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
            ResponseEntity<String> response = restTemplate.exchange(
                    builder.toUriString(),
                    HttpMethod.GET,
                    entity,
                    String.class
            );
            return response.getBody();
        } catch (UnsupportedEncodingException e) {
            throw new CustomException("Encoding issue: " + e.getMessage());
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
    }

}
